package com.tedu.egspringbootmvc.controller;

import com.tedu.egspringbootmvc.common.result.JsonResult;
import com.tedu.egspringbootmvc.common.result.StatusCode;
import com.tedu.egspringbootmvc.mapper.UserMapper;
import com.tedu.egspringbootmvc.pojo.dto.UserArticleDTO;
import com.tedu.egspringbootmvc.pojo.dto.UserDTO;
import com.tedu.egspringbootmvc.pojo.entity.User;
import com.tedu.egspringbootmvc.pojo.entity.UserArticle;
import com.tedu.egspringbootmvc.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("用户登录功能")
    @PostMapping("/login")
    public JsonResult userLogin(@RequestBody @Validated UserDTO userDTO,@ApiIgnore HttpSession session) {
        UserVO userVO = userMapper.selectUsernameAndPassword(userDTO.getUsername(), userDTO.getPassword());
        if (userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }else {
            session.setAttribute("userVo",userVO);
            return new JsonResult(StatusCode.OPERATION_SUCCESS);
        }
    }

    @ApiOperation("用户发表文章功能")
    @PostMapping("/article")
    public JsonResult publishedArticles(@RequestBody @Validated UserArticleDTO userArticleDTO,@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO)session.getAttribute("userVo");
        UserArticle userArticle = new UserArticle();
        BeanUtils.copyProperties(userArticleDTO,userArticle);
        userArticle.setUserId(userVO.getId());
        userMapper.insertUserArticle(userArticle);
        return new JsonResult(StatusCode.OPERATION_SUCCESS);
    }
    @ApiOperation("用户查询文章功能")
    @GetMapping("/selectByArticleId")
    public JsonResult selectByArticleId(@RequestParam Integer id){
        return new JsonResult(StatusCode.OPERATION_SUCCESS,userMapper.selectByArticleId(id));
    }
}
